#!/bin/sh

root_path='/vdb'
git_path='https://gitee.com/opengauss/openGauss-server.git'
branch='master'
compile_path=''
compile_user='lcover'
env_path='/home/lcover/env'
prefix='/vdb/openGauss_lys'
third_party_binarylibs_path='/vdb/openGauss-third_party_binarylibs'
workspace='/autotest_software/jenkins/workspace/lcov'

function download_source_code()
{
    date=`date '+%Y_%m_%d'`
    compile_path="$3/openGauss_$2_$date"
    git clone $1 -b $2 $compile_path
}

function compile_dubug()
{
    cd $1
    sed -i '/NotifyProcessActive();/i __gcov_flush();'  $1/src/gausskernel/process/postmaster/postmaster.cpp
    sed -i 'N;256 i extern "C" void __gcov_flush();'   $1/src/gausskernel/process/postmaster/postmaster.cpp
    ./configure --gcc-version=7.3.0 CC=g++ CFLAGS='-O0 -fprofile-arcs -ftest-coverage' --prefix=$2 --3rd=$3 --enable-debug --enable-cassert --enable-thread-safety --with-readline --without-zlib LDFLAGS='-lgcov'
    make -sj8
    make install -sj8
    if [ $? -ne 0 ]
    then
	return 1
    else
	echo "configure or make or make install failed"
    fi
}

function execute_fastcheck()
{
    cd $1
    make fastcheck_single
}

function collect_result()
{
    cd $1
    lcov --capture --directory . --output-file coverage.info
    sed -i "s|SF:\/src\/test\/whitebox\/knl_whitebox_test.cpp|SF:$1\/src\/test\/whitebox\/knl_whitebox_test.cpp|g" $1/coverage.info
    genhtml --no-prefix --no-sort coverage.info -o results
}

function copy_to_workspace()
{
    cd $1
    cp -rf results $workspace 
}

function env_prepare()
{
    local need_clean_source_code_path="/vdb/openGauss_$1*"
    rm -rf $prefix
    rm -rf $need_clean_source_code_path
}

function main()
{
    source $env_path
    env_prepare $branch
    if [ $? -ne 0 ]
    then
        echo "environment prepare failed"
	return 1
    else
        echo "environment prepare success"
    fi

    download_source_code $git_path $branch $root_path
    if [ $? -ne 0 ]
    then
        echo "download source code failed"
	return 1
    else
        echo "download source code success"
    fi

    compile_dubug $compile_path $prefix $third_party_binarylibs_path
    if [ $? -ne 0 ]
    then
        echo "compile debug version failed"
	return 1
    else
        echo "compile debug version success"
    fi

    execute_fastcheck $compile_path
    if [ $? -ne 0 ]
    then
        echo "execute fastcheck failed"
    else
        echo "execute fastcheck success"
    fi

    collect_result $compile_path
    if [ $? -ne 0 ]
    then
        echo "collect result failed"
	return 1
    else
        echo "collect result success"
    fi

    copy_to_workspace $compile_path
    if [ $? -ne 0 ]
    then
        echo "copy lcov results failed"
    else
        echo "copy lcov results success"
    fi
}

main $@
